package cn.tedu.ticket;
/**本类用于解决实现接口方式的售票安全隐患问题*/
public class TicketRunnableV2 {
    public static void main(String[] args) {
        /**target是统一的目标业务对象
         * 而Thread类对象t1,t2...是多个线程对象*/
        TicketRV2 target=new TicketRV2();
        Thread t1=new Thread(target);
        Thread t2=new Thread(target);
        Thread t3=new Thread(target);
        Thread t4=new Thread(target);
        t1.start();
        t2.start();
        t3.start();
        t4.start();


    }
}
class TicketRV2 implements Runnable{
    int tickets=100;
    Object o=new Object();
    public void run() {
        //循环结构
        while (true){
            //synchronized (new Object()){
            //1.解决方案:定义一个同步代码块注意所对象唯一
            synchronized (o){
                if (tickets>0){
                    try {
                    Thread.sleep(1000);//给程序主动设置休眠,制造阻塞,暴露数据安全问题
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                    System.out.println(Thread.currentThread().getName()+"="+tickets--);
                }
                if(tickets<=0)break;
            }

        }
    }
}